package cn.mothin.frame.util;

import java.lang.reflect.Field;

import org.apache.commons.logging.LogFactory;

public class ObjectUtil {
	/**
	 * 对象同步
	 * 
	 * @param target
	 *            目标对象
	 * @param src
	 *            源对象
	 */
	public static void SyncObjectWithoutFileds(Object target, Object src,
			String... ignoreFieldNames) {
		boolean ignore = false;
		Field[] fs = target.getClass().getDeclaredFields();
		for (Field f : fs) {
			String name = f.getName();
			if (ignoreFieldNames != null && ignoreFieldNames.length > 0) {
				ignore = false;
				for (String s : ignoreFieldNames) {
					if (s.equals(name)) {
						ignore = true;
						break;
					}
				}
				if (ignore) {
					continue;
				}
			}
			Field f_src = null;
			try {
				f_src = src.getClass().getDeclaredField(name);
				if (f_src == null) {
					continue;
				}
				if (!f_src.isAccessible()) {
					f_src.setAccessible(true);
				}
			} catch (Exception e) {
				LogFactory.getLog(ObjectUtil.class).error(e);
				continue;
			}
			try {
				if (!f.isAccessible()) {
					f.setAccessible(true);
				}
				f.set(target, f_src.get(src));
			} catch (Exception e) {
				LogFactory.getLog(ObjectUtil.class).error(e);
				continue;
			}
		}
	}

	public static void SyncObjectsWithFields(Object target, Object src,
			String... fieldNames) {
		boolean ignore = false;
		Field[] fs = target.getClass().getDeclaredFields();
		for (Field f : fs) {
			String name = f.getName();
			if (fieldNames != null && fieldNames.length > 0) {
				ignore = true;
				for (String s : fieldNames) {
					if (s.equals(name)) {
						ignore = false;
						break;
					}
				}
				if (ignore) {
					continue;
				}
			}
			Field f_src = null;
			try {
				f_src = src.getClass().getDeclaredField(name);
				if (f_src == null) {
					continue;
				}
				if (!f_src.isAccessible()) {
					f_src.setAccessible(true);
				}
			} catch (Exception e) {
				LogFactory.getLog(ObjectUtil.class).error(e);
				continue;
			}
			try {
				if (!f.isAccessible()) {
					f.setAccessible(true);
				}
				f.set(target, f_src.get(src));
			} catch (Exception e) {
				LogFactory.getLog(ObjectUtil.class).error(e);
				continue;
			}
		}
	}
}
